package com.wq.sofa.framework.bolt.server.processor;

import com.alipay.remoting.BizContext;
import com.alipay.remoting.Connection;
import com.alipay.remoting.rpc.RpcServer;
import com.alipay.remoting.rpc.protocol.SyncUserProcessor;
import com.wq.sofa.framework.bolt.model.CommonRequest;
import com.wq.sofa.framework.bolt.model.CommonRequest.DataBase;
import com.wq.sofa.framework.bolt.server.SimpleSynServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

/**
 * @Author: wangqiang20995
 * @Date:2018/9/19
 * @Description:
 * @Resource:
 */
public class LinuxProcessor extends SyncUserProcessor<CommonRequest> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private SimpleSynServer simpleSynServer;

    private int connectionTimes;

    public LinuxProcessor(SimpleSynServer simpleSynServer) {
        this.simpleSynServer = simpleSynServer;
        this.connectionTimes = 10;
    }

    public LinuxProcessor() {
    }

    @Override
    public Object handleRequest(BizContext bizContext, CommonRequest commonRequest) throws Exception {
        Byte code = commonRequest.getCode();
        String system = commonRequest.getSystem();
        logger.info("request system code [{}] and it's [{}]", code, system);
        Map<String, DataBase> data = new HashMap<>();
        DataBase mysql = commonRequest.generatorDataBase(1, "jdbc:mysql://localhost:3306/pay-union", "com.mysql.jdbc.Driver");
        data.put("mysql", mysql);
        commonRequest.setDataBaseMap(data);
        adviceByAsyn(bizContext.getConnection(), commonRequest);
        return commonRequest;
    }

    @Override
    public String interest() {
        return CommonRequest.class.getName();
    }

    private void adviceByAsyn(Connection connection, CommonRequest commonRequest) {
        if(this.simpleSynServer != null) {
            ExecutorService executorService = this.simpleSynServer.getExecutorService();

            if (CommonRequest.DUBLE_COMMUNICATION_CONNECTION == commonRequest.getCode()) {
                executorService.execute(() -> {
                    logger.info("send message to client initiative");
                    LinuxProcessor.this.simpleSynServer.transportInConnection(connection, 1);
                });
            }
        }else{
            logger.info("don't send message to client initiative");
        }
    }

    public void setSimpleSynServer(SimpleSynServer simpleSynServer) {
        this.simpleSynServer = simpleSynServer;
    }
}
